package wml.switcher.view;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.view.ViewGroup.LayoutParams;
import android.widget.ImageView;

public class MainView extends ImageView {

	private Canvas canvas;

	private Path path;
	private Paint paint;
	private float mX, mY;
	private static final float TOUCH_TOLERANCE = 4;
	private Matrix markMatrix = new Matrix();
	private Bitmap bitmap;
	private ViewController controller;

	public MainView(Context c) {
		super(c);
		this.paint = new Paint();

		this.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
				LayoutParams.FILL_PARENT));

		this.setScaleType(ScaleType.MATRIX);
		this.setFocusable(true);
		this.setPaintProperties();
	}
	
	public void setViewController(ViewController controller){
		this.controller = controller;
	}
	@Override
	protected void onDraw(Canvas c) {
		c.drawBitmap(this.bitmap, getImageMatrix(), paint);
		c.drawPath(path, paint);
	}

	protected void touch_start(float x, float y) {
		path.moveTo(x, y);
		mX = x;
		mY = y;
	}

	protected void touch_move(float x, float y) {
		float dx = Math.abs(x - mX);
		float dy = Math.abs(y - mY);

		if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
			path.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
			mX = x;
			mY = y;
		} else {
			path.lineTo(x, y);
		}
	}

	protected void touch_up() {
		path.lineTo(mX, mY);
		path.transform(markMatrix);
		canvas.drawPath(path, paint);
		this.controller.addPath(new Path(this.path));
		this.path.reset();
	}

	private void setPaintProperties() {
		paint.setAntiAlias(true);
		paint.setDither(true);
		paint.setColor(0xFFFF0000);
		paint.setStyle(Paint.Style.STROKE);
		paint.setStrokeJoin(Paint.Join.ROUND);
		paint.setStrokeCap(Paint.Cap.ROUND);
		paint.setStrokeWidth(1);
	}

	public void setView(Bitmap bitmap, Path path) {
		if (this.bitmap != null){
			this.bitmap.recycle();
			System.gc();
		}
		this.bitmap = bitmap;
		this.path = path;
		canvas = new Canvas(this.bitmap);
		canvas.drawPath(path, paint);
		this.path.reset();
		this.invalidate();
	}

	@Override
	public void setImageMatrix(Matrix matrix) {
		super.setImageMatrix(matrix);
		this.getImageMatrix().invert(this.markMatrix);
	}

	public Matrix getMarkMatrix() {
		return this.markMatrix;
	}

	class RefreshRunnable implements Runnable {
		@Override
		public void run() {
			MainView.this.postInvalidate();
		}
	}
}